<template>
  <div class="sacrificeOnBehalfOf h100" v-loading="loading">
    <div class="pageContent">
      <el-row :gutter="11" class="fileSearch">
        <el-form :model="ruleForm" :inline="true" ref="ruleForm" label-width="100px">
          <el-form-item label="预约人姓名:" prop="appointmentName">
            <el-input v-model="ruleForm.appointmentName" clearable></el-input>
          </el-form-item>
          <el-form-item
            label-width="120px"
            label="预约人联系方式:"
            prop="appointmentPhone"
          >
            <el-input v-model="ruleForm.appointmentPhone" clearable></el-input>
          </el-form-item>

          <el-form-item label="逝者姓名:" prop="deadName">
            <el-input v-model="ruleForm.deadName" clearable></el-input>
          </el-form-item>
          <el-form-item label="订单状态:" prop="sweepOrderState">
            <el-select v-model="ruleForm.sweepOrderState" placeholder="请选择纪念馆状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="用户取消" :value="0"></el-option>
              <el-option label="工作人员取消" :value="1"></el-option>
              <el-option label="待审核" :value="2"></el-option>
              <el-option label="审核成功,待支付" :value="3"></el-option>
              <el-option label="支付成功" :value="4"></el-option>
              <el-option label="完成" :value="5"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onSubmit(1)">
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-table
        :data="tableData"
        border
        :header-cell-style="{
          background: 'rgb(246,247,251)',
          color: '#606266',
        }"
        stripe
        class="defaultTableHeight"
      >
        <el-table-column type="index" label="编号" width="50"> </el-table-column>
        <el-table-column prop="orderNo" align="center" label="订单号" width="190">
        </el-table-column>

        <el-table-column prop="appointmentName" align="center" label="预约人姓名">
        </el-table-column>
        <el-table-column prop="appointmentPhone" align="center" label="预约人联系方式">
        </el-table-column>
        <el-table-column
          prop="appointmentCardNo"
          align="center"
          label="预约人身份证号"
          width="190"
        >
        </el-table-column>
        <el-table-column prop="deadName" align="center" label="逝者姓名">
        </el-table-column>
        <el-table-column prop="deadCardNo" align="center" label="逝者身份证号">
        </el-table-column>
        <el-table-column prop="graveDetail" align="center" label="墓穴具体位置">
        </el-table-column>
        <el-table-column prop="appointmentDate" align="center" label="预约日期">
        </el-table-column>
        <!-- <el-table-column align="center" label="预约日期">
          <template slot-scope="{row}">
            {{row.appointmentDate | timestampToTime}}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="订单状态">
          <template slot-scope="scope">
            {{ scope.row.sweepOrderState | formatStatus(scope.row.orderType) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.sweepOrderState == 2"
              type="primary"
              size="mini"
              @click="changeStatus(scope.row, 3)"
              >审核</el-button
            >
            <el-button
              v-if="scope.row.sweepOrderState == 4"
              type="primary"
              size="mini"
              @click="uploadBtn(scope.row)"
              >上传图片</el-button
            >

            <!-- <el-button
              v-if="scope.row.sweepOrderState == 4"
              type="danger"
              size="mini"
              @click="changeStatus(scope.row, 5)"
              >完成</el-button
            > -->
            <el-button
              v-if="scope.row.sweepOrderState == 2 || scope.row.sweepOrderState == 3"
              type="danger"
              size="mini"
              @click="delOrder(scope.row, 1)"
              >取消</el-button
            >
            <el-button type="success" size="mini" @click="orderDetails(scope.row.id)"
              >订单详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <p style="text-align: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pager.currentPage"
          :page-size="pager.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total,sizes,prev, pager, next, jumper"
          :total="pager.total"
        >
        </el-pagination>
      </p>
    </div>
    <el-dialog
      title="上传图片"
      :visible.sync="dialogVisible"
      width="600px"
      v-dialogDrag
      @close="closeDialog(0)"
    >
      <el-form ref="goodsForm" :model="goodsForm" label-width="80px">
        <el-form-item label="上传图片" prop="title">
          <!-- <el-input v-model="goodsForm.images.length" readonly> -->
          <div>
            <el-button @click="imgClick">选择图片 </el-button>
          </div>
          <!-- </el-input> -->
          <div
            class="del_img"
            v-for="(item, index) in goodsForm.images"
            :key="index"
            @mouseover="delSpan(0, index)"
            @mouseout="delSpan(1, index)"
          >
            <span style="display: none" class="del_span" @click="delImgClick(index)"
              >点击删除</span
            >
            <img v-if="goodsForm.images.length > 0" class="file_img" :src="item" />
          </div>
          <input
            class="file_input"
            type="file"
            accept=".png,.jpg,.jpeg"
            @change="change"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadImg" :loading="uploadImgLoading"
            >上传并完成订单</el-button
          >
          <el-button @click="closeDialog(0)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="订单详情"
      :visible.sync="dialogVisibleDetails"
      width="600px"
      v-dialogDrag
      @close="closeDialog(1)"
    >
      <div class="DetailsList_dialog">
        <el-form ref="DetailsList" :model="DetailsList" label-width="100px">
          <el-form-item label="订单号">
            <el-input v-model="DetailsList.orderNo" readonly></el-input>
          </el-form-item>
          <el-form-item label="当前订单状态">
            <el-tag
              :type="
                DetailsList.sweepOrderState == 0 || DetailsList.sweepOrderState == 1
                  ? 'danger'
                  : DetailsList.sweepOrderState == 2
                  ? 'warning'
                  : 'success'
              "
            >
              {{ DetailsList.sweepOrderState | formatStatus(DetailsList.orderType) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="逝者姓名">
            <el-input v-model="DetailsList.deadName" readonly></el-input>
          </el-form-item>
          <el-form-item label="逝者身份证">
            <el-input v-model="DetailsList.deadCardNo" readonly></el-input>
          </el-form-item>
          <el-form-item label="预约人姓名">
            <el-input v-model="DetailsList.appointmentName" readonly></el-input>
          </el-form-item>
          <el-form-item label="预约人电话">
            <el-input v-model="DetailsList.appointmentPhone" readonly></el-input>
          </el-form-item>
          <el-form-item label="墓穴信息">
            <el-input v-model="DetailsList.graveDetail" readonly></el-input>
          </el-form-item>
          <el-form-item label="预约日期">
            <el-input v-model="DetailsList.appointmentDate" readonly></el-input>
          </el-form-item>
          <el-form-item label="关联图片">
            <span v-if="!DetailsList.fileUrls || DetailsList.fileUrls.length <= 0"
              >暂无关联图片</span
            >
            <el-image
              v-if="DetailsList.fileUrls || DetailsList.fileUrls.length > 0"
              class="DetailsList_img"
              v-for="(item, index) in DetailsList.fileUrls"
              :key="index"
              :src="item"
              :preview-src-list="DetailsList.fileUrls"
            ></el-image>
          </el-form-item>
          <el-form-item label="基础服务费">
            <el-input v-model="DetailsList.osPrice" readonly></el-input>
          </el-form-item>
          <el-form-item label="祭扫商品">
            <span v-if="!DetailsList.orderSpus || DetailsList.orderSpus.length <= 0"
              >暂无祭扫商品</span
            >
            <div
              v-if="DetailsList.orderSpus || DetailsList.orderSpus.length > 0"
              class="goods"
              v-for="(item, index) in DetailsList.orderSpus"
              :key="index"
            >
              <div class="good_img">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="item.img"
                  fit="cover"
                ></el-image>
              </div>
              <div class="good_info">
                <span>商品名称:{{ item.spuName }}</span>
                <span>价格:{{ item.price }}</span>
                <span>数量：{{ item.num }}</span>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="block">
          <el-timeline reverse>
            <!-- 倒序排列 -->
            <el-timeline-item
              v-for="(item, index) in DetailsList.orderTurnLogs"
              :key="index"
              :timestamp="item.gmtCreate | timestampToTime"
              placement="top"
            >
              <el-card>
                <div>
                  订单状态 :
                  <el-tag
                    :type="
                      item.orderState == 0 || item.orderState == 1
                        ? 'danger'
                        : item.orderState == 2
                        ? 'warning'
                        : 'success'
                    "
                  >
                    {{ item.orderState | formatStatus(item.orderType) }}
                  </el-tag>
                </div>

                <p>
                  {{ item.userName }} 创建于
                  {{ item.gmtCreate | timestampToTime }}
                </p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  orderSacrificeManage_grave,
  orderSacrificeManage_operation,
  orderSacrificeManage_upload,
  orderSacrificeManage_details,
} from "@/api/appUser/sacrificeOnBehalfOf";
export default {
  name: "sacrificeOnBehalfOf",
  data() {
    return {
      loading: false,
      dialogVisible: false, // 上传弹窗
      dialogVisibleDetails: false, // 详情弹窗
      uploadImgLoading: false, //上传按钮
      ruleForm: {
        appointmentName: "",
        appointmentPhone: "",
        deadName: "",
        sweepOrderState: "",
      },
      goodsForm: {
        id: "",
        orderNo: "",
        images: [],
        type: "image",
      },
      info: {}, // 保存当前操作的数据
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1,
      },
      tableData: [],
      DetailsList: {}, // 详情列表
    };
  },
  filters: {
    // formatStatus(val) {
    //   // let num = +val;
    //   switch (val) {
    //     case 0:
    //       return "用户取消";
    //       break;
    //     case 1:
    //       return "工作人员取消";
    //       break;
    //     case 2:
    //       return "待审核";
    //       break;
    //     case 3:
    //       return "审核成功,待支付";
    //       break;
    //     case 4:
    //       return "支付成功";
    //       break;
    //     case 5:
    //       return "完成";
    //       break;
    //   }
    // },
    formatStatus(val, type) {
      if (val == 0) {
        return "用户取消";
      } else if (val == 1) {
        return "工作人员取消";
      } else if (val == 2) {
        return "待审核";
      } else if (val == 3) {
        return "审核成功,待支付";
      } else if (val == 4 && type == 0) {
        return "免费祭扫";
      } else if (val == 4 && type == 1) {
        return "支付成功";
      } else if (val == 5) {
        return "完成";
      }
    },
    timestampToTime(date) {
      var nowdate = new Date(date).toJSON().substr(0, 19).replace("T", " ");
      return nowdate;
    },
  },
  mounted() {
    this.onSubmit();
  },
  methods: {
    // 取消确认
    delOrder(info, state) {
      let that = this;
      this.$confirm("此操作将取消该订单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          that.changeStatus(info, state);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    //更改状态
    async changeStatus(info, state) {
      let postData = {
        id: info.id,
        version: info.version,
        sweepOrderState: state,
      };
      console.log(postData, "postData");
      try {
        const res = await orderSacrificeManage_operation(postData);
        console.log(res, 200);
        if (res.code !== "2000") {
          this.$message.error(
            res.msg
            // state == 1 ? "取消失败" : state == 3 ? "审核失败" : "操作失败"
          );
          this.onSubmit();
          return;
        }
        this.$message.success(
          state == 1 ? "取消成功" : state == 3 ? "审核成功" : "操作成功"
        );
        this.onSubmit();
      } catch (err) {
        console.log(err, 404);
        this.$message.error(err.msg);
      }
    },

    //列表加载
    async onSubmit(val) {
      if (val) {
        this.pager.currentPage = 1;
      }
      this.loading = true;
      let postData = {
        // name: this.ruleForm.name,
        appointmentName: this.ruleForm.appointmentName,
        appointmentPhone: this.ruleForm.appointmentPhone,
        deadName: this.ruleForm.deadName,
        sweepOrderState: this.ruleForm.sweepOrderState,
        pageSize: this.pager.pageSize,
        currentPage: this.pager.currentPage,
      };
      try {
        //查询接口
        let res = await orderSacrificeManage_grave(postData);
        this.loading = false;
        if (res.code !== "2000") {
          this.$message.error(res.msg ? res.msg : "数据读取失败");
          return;
        }
        this.tableData = res.data;
        this.pager.pageSize = res.pageSize;
        this.pager.total = res.total;
        this.pager.currentPage = res.currentPage;
      } catch (err) {
        this.loading = false;
        console.log(err, 404);
        this.$message.error(err.msg);
      }
    },

    // 上传按钮点击事件
    uploadBtn(info) {
      this.info = info;
      this.goodsForm.id = info.id;
      this.goodsForm.orderNo = info.orderNo;
      this.dialogVisible = true;
    },

    // 触发图片选择
    imgClick() {
      if (this.goodsForm.images.length >= 3) {
        this.$message("最多只能上传三张图片");
        return;
      }
      document.querySelector("input[type=file]").value = "";
      document.querySelector("input[type=file]").click();
    },
    // 选择图片
    change() {
      let file = document.querySelector("input[type=file]").files[0];
      var reader = new FileReader();
      var that = this;
      console.log("base64", file);
      reader.onloadend = function () {
        //把转换后的数据给id为base64Img的src属性
        console.log(reader.result);
        that.goodsForm.images.push(reader.result);
        //这里调用了向后台发请求的代码
      };
      if (file) {
        reader.readAsDataURL(file);
      }
      document.querySelector("input[type=file]").value = "";
    },
    delSpan(val, i) {
      if (val) {
        document.querySelectorAll(".del_span")[i].style.display = "none";
      } else {
        document.querySelectorAll(".del_span")[i].style.display = "block";
      }
    },
    // 删除选择的图片
    delImgClick(index) {
      this.goodsForm.images.splice(index, 1);
    },
    //上传图片
    async uploadImg(info) {
      let postData = this.goodsForm;
      if (postData.images.length <= 0) {
        this.$message("请选择需要上传的图片");
        return;
      }
      this.loading = true;
      this.uploadImgLoading = true;
      console.log(postData, "postData");
      try {
        const res = await orderSacrificeManage_upload(postData);
        console.log(res, 200);
        this.uploadImgLoading = false;
        this.loading = false;
        if (res.code !== "2000") {
          this.$message.error(res.msg ? res.msg : "图片上传失败");
          return;
        }
        // this.onSubmit();
        this.$message.success("图片上传成功");
        this.dialogVisible = false;
        this.changeStatus(this.info, 5);
      } catch (err) {
        this.loading = false;
        this.uploadImgLoading = false;
        console.log(err, 404);
        this.$message.err(err.msg);
      }
    },

    // 订单详情查询
    async orderDetails(id) {
      this.loading = true;
      let postData = { id };
      console.log(postData, "postData");
      try {
        const res = await orderSacrificeManage_details(postData);
        console.log(res, 200);
        this.loading = false;
        this.dialogVisibleDetails = true;
        if (res.code !== "2000") {
          this.$message.error(res.msg ? res.msg : "订单详情获取失败");
          return;
        }
        this.$message.success("订单详情获取成功");
        this.DetailsList = res.data;
        this.DetailsList.osPrice = this.DetailsList.osPrice / 100;
        this.DetailsList.appointmentDate = new Date(
          res.data.appointmentDate + 8 * 60 * 60 * 1000
        )
          .toJSON()
          .substr(0, 19)
          .replace("T", " ");
      } catch (err) {
        this.loading = false;
        this.$message.error(err.msg);
        console.log(err, 404);
      }
    },

    // 关闭弹窗的回调
    closeDialog(val) {
      if (val == 0) {
        this.goodsForm = {
          id: "",
          orderNo: "",
          images: [],
          type: "image",
        };
        this.$refs["goodsForm"].resetFields();
        this.dialogVisible = false;
      } else {
        this.DetailsList = {};
        this.dialogVisibleDetails = false;
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["ruleForm"].resetFields();
      this.onSubmit();
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pager.pageSize = size;
      this.onSubmit();
    },
    handleCurrentChange: function (currentPage) {
      this.pager.currentPage = currentPage;
      this.onSubmit(); //点击第几页
    },
  },
};
</script>

<style lang="scss" scoped>
.del_img {
  display: inline-block;
  position: relative;
  width: 200px;
  height: 200px;
  margin-top: 10px;
  margin-right: 10px;
}
.del_span {
  // display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.452);
  text-align: center;
  line-height: 200px;
  color: #fff;
  cursor: pointer;
}

.file_img {
  width: 200px;
  height: 200px;
  // cursor: pointer;
}
.file_input {
  color: #ffffff00;
  display: none;
  width: 100px;
  height: 100px;
}

.DetailsList_dialog {
  height: 600px;
  overflow-y: auto;
  margin-right: -20px;
  padding-right: 20px;
}
.DetailsList_img {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}
.goods {
  display: flex;
  align-items: center;
  .good_img {
    margin-right: 10px;
  }
  .good_info {
    flex: 1;
    display: flex;
    flex-direction: column;
    span {
      line-height: 30px;
    }
  }
}
</style>
